﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using RTSoft.SoureCode.Control.KhachHang;
using RTSoft.SoureCode.Control.HoaDon;
using DevExpress.XtraGrid;
using RTSoft.SoureCode.Control.ChiTietHD;
using RTSoft.SoureCode.Control.HangHoa;
using RTSoft.SoureCode.Control.DonGiaBan;
using RTSoft.Modules;
using RTSoft.SoureCode.Control.NhanVien;
using RTSoft.SoureCode.Report;

namespace RTSoft.SoureCode.Entity
{
    public partial class frmXuatHang : DevExpress.XtraEditors.XtraForm
    {
        public frmXuatHang()
        {
            InitializeComponent();
        }
        DataTable tbl;
        String errConnect;
        String errSQL;
        int total = 0;
            

        private void frmXuatHang_Load(object sender, EventArgs e)
        {
            try
            {
                InitGrid();
                InitGridDetail();
                
                this.txtPrice.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                this.txtPrice.Properties.DisplayFormat.FormatString = "###,###,##0";
           
            }
            catch {
                Library.ShowMessage("Lỗi dữ liệu đầu vào");
            }
        }

        #region "Load Grid Hóa Đơn"
        public void InitGrid()
        {
            tbl = new DataTable();
            errConnect = "";
            errSQL = "";
            hoadonctrl ctrl = new hoadonctrl();
            ctrl.getData(ref errConnect, ref errSQL, ref tbl);
            GridControl1.DataSource = tbl;
            GridView1.Columns["ID_HD"].Caption = "ID";
            GridView1.Columns["ID_NV"].Caption = "Người lập";
            GridView1.Columns["ID_NV"].Visible = false;
            GridView1.Columns["ID_KH"].Caption = "Khách Hàng";
            GridView1.Columns["THANHTIEN"].Caption = "Tổng Tiền";
            GridView1.Columns["NGAY_TAO"].Caption = "Ngày Tạo";
            GridView1.Columns["NGAY_TAO"].OptionsColumn.ReadOnly = true;
            GridView1.Columns["TRANGTHAI"].Caption = "Trạng Thái";
            GridView1.Columns["TRANGTHAI"].OptionsColumn.ReadOnly = true;
            
            GridView1.Columns["THANHTIEN"].OptionsColumn.ReadOnly = true;
            GridView1.Columns["ID_HD"].Visible = false;
            GridView1.BestFitColumns();

            GridView1.Columns["THANHTIEN"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            GridView1.Columns["THANHTIEN"].DisplayFormat.FormatString = "###,###,##0";
            
            RepositoryItemGridLookUpEdit riCombo = new RepositoryItemGridLookUpEdit();
            DataTable tblCus = new DataTable();
            khachhangctrl ctrlCus = new khachhangctrl();
            ctrlCus.getData(ref errConnect, ref errSQL, ref tblCus);
            riCombo.DataSource = tblCus;
            riCombo.ValueMember = "ID_KH";
            riCombo.DisplayMember = "TEN_KH";
            riCombo.View.Columns["ID_KH"].Caption = "Tên Khách Hàng";
            riCombo.View.Columns["ID_KH"].Visible = false;
            riCombo.View.Columns["SDT_KH"].Visible = false;
            riCombo.View.Columns["CMND_KH"].Visible = false;
            riCombo.View.Columns["DIEM"].Visible = false;
            riCombo.View.Columns["ID_KH"].OptionsFilter.AllowAutoFilter = true;
            riCombo.View.Columns["ID_KH"].OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            riCombo.View.OptionsView.ShowAutoFilterRow = true;
            GridControl1.RepositoryItems.Add(riCombo);
            GridView1.Columns["ID_KH"].ColumnEdit = riCombo;

            StyleFormatCondition styleCondition = new StyleFormatCondition();
            styleCondition.Column = GridView1.Columns["TRANGTHAI"];
            styleCondition.Condition = FormatConditionEnum.Expression;
            styleCondition.Expression = "[TRANGTHAI] != 1";
            styleCondition.Appearance.Font = new Font(GridView1.Appearance.Row.Font, FontStyle.Bold);
            styleCondition.Appearance.ForeColor = Color.Red;
            styleCondition.Appearance.Options.UseFont = true;
            styleCondition.Appearance.Options.UseForeColor = true;
            // Add the style condition to the collection 
            GridView1.FormatConditions.Add(styleCondition);

            hanghoactrl ctrlI = new hanghoactrl();
            DataTable tblI = new DataTable();
            ctrlI.getDataBySelect(ref errConnect, ref errSQL, ref tblI, "ID_MATHANG,TEN_MATHANG");
            this.riCombo.Properties.DataSource = tblI;
            this.riCombo.Properties.DisplayMember = "TEN_MATHANG";
            this.riCombo.Properties.ValueMember = "ID_MATHANG";
            this.riCombo.Properties.View.Columns["ID_MATHANG"].Visible = false;
            this.riCombo.Properties.View.Columns["TEN_MATHANG"].Caption = "Mặt hàng";
            
            this.riCombo.Properties.View.Columns["TEN_MATHANG"].OptionsFilter.AllowAutoFilter = true;
            this.riCombo.Properties.View.Columns["TEN_MATHANG"].OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            
            
        }

        private void GridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            try
            {
                int iRow = e.RowHandle;
                GridView1.SetRowCellValue(iRow, "NGAY_TAO", DateTime.Now);
                GridView1.SetRowCellValue(iRow, "THANHTIEN", 0);
                GridView1.SetRowCellValue(iRow, "TRANGTHAI", "Chưa thanh toán");
                GridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
            }
            catch {
                Library.ShowMessage("Lỗi dữ liệu!");
            }
        }

        #endregion

        #region "Load Grid Chi tiết Hóa Đơn"
        public void InitGridDetail()
        {
            tbl = new DataTable();
            errConnect = "";
            errSQL = "";
            chitiethdctrl ctrl = new chitiethdctrl();
            ctrl.getHeader(ref errConnect, ref errSQL, ref tbl);
            gridControl2.DataSource = tbl;
            gridItem.Columns["ID_HD"].Caption = "ID";
            gridItem.Columns["ID_MATHANG"].Caption = "ID_MH";
            gridItem.Columns["TEN_MATHANG"].Caption = "Mặt Hàng";
            gridItem.Columns["SOLUONG_BAN"].Caption = "Số Lượng";
            gridItem.Columns["DONGIA"].Caption = "Đơn Giá";
            gridItem.Columns["THANHTIEN"].Caption = "Thành Tiền";
            gridItem.Columns["ID_HD"].Visible = false;
            gridItem.Columns["ROW_ID"].Visible = false;
            gridItem.Columns["ID_MATHANG"].Visible = false;

            gridItem.Columns["DONGIA"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            gridItem.Columns["DONGIA"].DisplayFormat.FormatString = "###,###,##0";

            gridItem.Columns["THANHTIEN"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            gridItem.Columns["THANHTIEN"].DisplayFormat.FormatString = "###,###,##0";

            //Tính tổng tiền            
            gridItem.Columns["THANHTIEN"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridItem.Columns["THANHTIEN"].SummaryItem.DisplayFormat = "Tổng tiền: {0:###,###,##0} VNĐ";
        }       
        #endregion  
       
               
        #region "event Button"

        // Chọn sản phẩm tự động cập nhật giá
        private void riCombo_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                dongia_banctrl ctrl = new dongia_banctrl();
                hanghoactrl Itemctrl = new hanghoactrl();
                errConnect = "";
                errSQL = "";
                txtNumber.EditValue = 0;
                txtNumber.Focus();
                txtPrice.Text = ctrl.getPrice(ref errConnect, ref errSQL, Convert.ToInt32(riCombo.EditValue)).ToString();
                txtQuantity.Text = Itemctrl.getQuantity(ref errConnect, ref errSQL, Convert.ToInt32(riCombo.EditValue)).ToString();
                if (Convert.ToInt32(txtQuantity.Text) != 0)
                {
                    txtStatus.Text = "Còn hàng";
                    txtStatus.ForeColor = Color.Blue;
                }
                else {
                    txtStatus.Text = "Hết hàng";
                    txtStatus.ForeColor = Color.Red;
                }
            }
            catch {
                Library.ShowMessage("Lỗi khi lấy giá và số lượng");
            }
        }

        // Thêm sản phẩm vào hóa đơn
        private void btnSave_Click(object sender, EventArgs e)
        {
           
            int iRow = GridView1.RowCount - 1;
            int sl = 0;
            if (iRow >= 0)
            {
                int jRow = gridItem.RowCount - 1;
                if (jRow >= 0) {
                    for (int i = 0; i <= jRow; i++) 
                    {
                        gridItem.FocusedRowHandle = i;    
                        int id_mh = Convert.ToInt32(gridItem.GetRowCellValue(i,"ID_MATHANG"));
                        if (id_mh == Convert.ToInt32(riCombo.EditValue)) 
                        {
                            sl += Convert.ToInt32(gridItem.GetRowCellValue(i, "SOLUONG_BAN"));
                            if (Convert.ToInt32(gridItem.GetRowCellValue(i, "SOLUONG_BAN")) < Convert.ToInt32(txtQuantity.Text))
                            {
                                gridItem.SetRowCellValue(i, "SOLUONG_BAN", sl + Convert.ToInt32(txtNumber.Text));
                                gridItem.SetRowCellValue(i, "THANHTIEN", (sl + Convert.ToInt32(txtNumber.Text))*Convert.ToInt32(gridItem.GetRowCellValue(i, "DONGIA")));
                                return;
                            }
                            else 
                            {
                                Library.ShowMessage("Trong kho chỉ còn " + txtQuantity.Text + "!");
                            }
                        }
                    }
                }
                if (Convert.ToInt32(txtNumber.Text) <= 0)
                {
                    Library.ShowMessage("Vui lòng nhập số lượng!");
                    txtNumber.Focus();
                }
                else if (Convert.ToInt32(txtNumber.Text)+sl > Convert.ToInt32(txtQuantity.Text))
                {
                    Library.ShowMessage("Trong kho chỉ còn " + txtQuantity.Text + "!");
                    txtNumber.Text = "0";
                    txtNumber.Focus();
                }
                else 
                {
                    this.gridItem.AddNewRow();
                }
            }
            else
            {
                Library.ShowMessage("Vui lòng chọn khách hàng!");                
            }

        }

        //thêm dữ liệu offline vào datagridItem
        private void gridItem_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            try
            {
                
                this.gridItem.SetRowCellValue(e.RowHandle, "ID_MATHANG", this.riCombo.EditValue);
                this.gridItem.SetRowCellValue(e.RowHandle, "TEN_MATHANG", this.riCombo.Text);
                this.gridItem.SetRowCellValue(e.RowHandle, "SOLUONG_BAN", RTValidate.ZeroNull(txtNumber.Text));
                this.gridItem.SetRowCellValue(e.RowHandle, "DONGIA", txtPrice.EditValue);
                this.gridItem.SetRowCellValue(e.RowHandle, "THANHTIEN", Convert.ToInt32(txtNumber.EditValue) * Convert.ToInt32(txtPrice.EditValue));                
                this.gridItem.SetFocusedRowModified();
            }
            catch
            {
                Library.ShowMessage("Kiểm tra dữ liệu nhập vào");
            }
        }

        //Thanh toán
        private void btnCheckin_Click(object sender, EventArgs e)
        {
            if (gridItem.RowCount < 0)
            {
                MessageBox.Show("Vui lòng chọn sản phẩm cần lập hóa đơn!");
                return;
            }
            for (int i = 0; i < gridItem.RowCount; i++)
            {
                gridItem.FocusedRowHandle = i;
                total += Convert.ToInt32(gridItem.GetRowCellValue(i, "THANHTIEN"));
            }
            GridView1.SetFocusedRowCellValue("THANHTIEN", total);
            GridView1.SetFocusedRowCellValue("TRANGTHAI", "Đã thanh toán");
            btnSave.Enabled = false;
            btnPrint.Enabled = true;
            formClear(1);
        }
        
        //In hóa đơn
        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                //insert hóa đơn
                this.insertBill();
                //insert chi tiết hóa đơn
                this.insertbillDetail();
                //Cập nhật điểm cho khách hàng dựa vào tổng tiền của hóa đơn 10,000đ = 1 điểm
                this.updateCusPoint();
                //Cập nhật lại số lượng của hàng sau khi xuất

                this.print();
                //Hoàn tất quá trình xuất hàng cập nhật lại 2 gridView
                total = 0;
                this.InitGrid();
                this.InitGridDetail();
                GridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
                btnSave.Enabled = true;
                formClear(2);
            }
            catch (Exception ex)
            {
                Library.ShowMessage(ex.Message);
            }
        }
        
        //Xóa sản phẩm + khách hàng
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gridItem.RowCount > 0)
            {
                gridItem.DeleteSelectedRows();
            }
            else
            {
                GridView1.DeleteSelectedRows();
                GridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Top;
            }

        }
        
        //Thoát
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        #endregion

        #region "Thêm Hóa đơn + Chi tiết hóa đơn"

        public void insertBill() {
            hoadonctrl ctrl = new hoadonctrl();
            hoadoninfo info = new hoadoninfo();
            nhanvienctrl ctrlEmp = new nhanvienctrl();

            errConnect = "";
            errSQL = "";
            DataRow row = GridView1.GetDataRow(0);
            //lấy id nhân viên dựa vào tên đăng nhập
            info.ID_NV = ctrlEmp.getID(ref errConnect, ref errSQL, RTValidate.RTUser);
            info.ID_KH = Convert.ToInt32(RTValidate.CheckNull(row["ID_KH"]));
            info.THANHTIEN = Convert.ToInt32(RTValidate.CheckNull(row["THANHTIEN"]));
            info.NGAY_TAO = Convert.ToDateTime(row["NGAY_TAO"]);
            info.TRANGTHAI = 1;
            ctrl.Insert(ref errConnect, ref errSQL, info);
        }

        public void insertbillDetail() {
            hoadonctrl ctrl = new hoadonctrl();
            chitiethdctrl ctrlDetail = new chitiethdctrl();
            for (int i = 0; i < gridItem.RowCount; i++)
            {
                gridItem.FocusedRowHandle = i;
                chitiethdinfo infoDetail = new chitiethdinfo();
                errConnect = "";
                errSQL = "";
                //lấy id hóa đơn max
                infoDetail.ID_HD = ctrl.getID(ref errConnect, ref errSQL);
                infoDetail.ID_MATHANG = Convert.ToInt32(gridItem.GetRowCellValue(i, "ID_MATHANG"));
                infoDetail.SOLUONG_BAN = Convert.ToInt32(gridItem.GetRowCellValue(i, "SOLUONG_BAN"));
                infoDetail.DONGIA = Convert.ToInt32(gridItem.GetRowCellValue(i, "DONGIA"));
                infoDetail.THANHTIEN = Convert.ToInt32(gridItem.GetRowCellValue(i, "THANHTIEN"));
                ctrlDetail.Insert(ref errConnect, ref errSQL, infoDetail);
                if (errSQL != "") {
                    MessageBox.Show(errSQL);
                    return;
                }
                //Cập nhật lại số lượng tồn kho của sản phẩm vừa bán
                ctrlDetail.UpdateQuantity(ref errConnect, ref errSQL, infoDetail.ID_MATHANG, infoDetail.SOLUONG_BAN);
            }
        }

       

        public void updateCusPoint() {
            khachhangctrl ctrlCus = new khachhangctrl();
            khachhanginfo infoCus = new khachhanginfo();
            errConnect = "";
            errSQL = "";
            infoCus.ID_KH = Convert.ToInt32(GridView1.GetRowCellValue(0, "ID_KH"));
            if (infoCus.ID_KH != 1)
            {
                if (Convert.ToInt32(total / 10000) >= 1)
                {
                    infoCus.DIEM = ctrlCus.getPoint(ref errConnect, ref errSQL, infoCus.ID_KH) + Convert.ToInt32(total / 10000);
                    ctrlCus.UpdatePoint(ref errConnect, ref errSQL, infoCus);
                }
            }
        }

        public void print() {
            rptHoaDon report = new rptHoaDon();
            frmShowReport dlg = new frmShowReport();
            DataTable dt = new DataTable();
            errConnect = "";
            errSQL = "";
            chitiethdctrl ctrl = new chitiethdctrl();
            ctrl.getDataReport(ref errConnect, ref errSQL, ref dt);
            report.DataSource = dt;
            //Nhập dữ liệu lên report
            report.cellstt.DataBindings.Add("Text", dt, "STT");
            report.cellID.DataBindings.Add("Text", dt, "ID_HD");
            report.cellItem.DataBindings.Add("Text", dt, "TEN_MATHANG");
            report.cellQuantity.DataBindings.Add("Text", dt, "SOLUONG_BAN");
            report.cellDate.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            report.cellPrice.DataBindings.Add("Text", dt, "DONGIA", "{0:###,###,##0.###}");
            report.cellAmount.DataBindings.Add("Text", dt, "THANHTIEN", "{0:###,###,##0.###}");
            report.cellCreateBy.Text = RTValidate.RTUser;
            DevExpress.XtraReports.UI.XRSummary XrSummary1 = new DevExpress.XtraReports.UI.XRSummary();
            report.cellTotal.DataBindings.Add("Text", dt, "THANHTIEN", "{0:###,###,##0.###}");
            XrSummary1 = new DevExpress.XtraReports.UI.XRSummary();
            XrSummary1.FormatString = "{0:###,###,##0.#### VNĐ}";
            XrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.Sum;
            XrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report;
            report.cellTotal.Summary = XrSummary1;

            double vat = total * 0.1;
            report.cellVAT.Text = vat.ToString("###,###,##0.#### VNĐ");

            report.cellTotalAmount.Text = (total + vat).ToString("###,###,##0.#### VNĐ");           

            dlg.printControl1.PrintingSystem = report.PrintingSystem;
            report.CreateDocument();
            dlg.Name = "Xuất hàng";
            dlg.Show();
        }

        #endregion

        private void formClear(int level) {
            if (level < 2)
            {
                riCombo.EditValue = null;
                txtNumber.Text = "";
                txtQuantity.Text = "";
                txtPrice.Text = "";
                txtStatus.Text = "";
            }
            else {
                this.InitGrid();
                this.InitGridDetail();
            }

        }



    }
}